<template>
  <div class="canvas">
    <header class="header">
      <div class="title">
        <img src="../../../assets/images/01_11.png" alt class="img_zuo" @click="jumpReturn" />
        <div>{{ routers === '/signature_be_list' ? '被检查人签名' : '检查人签名' }}</div>
      </div>
    </header>
    <div class="canvas-box">
      <div id="canvas"></div>
      <div class="canvas-btn">
        <div class="canvas-btn-box">
          <div class="btns" id="clearCanvas">清除</div>
          <div class="btns" @click="jumpReturn">关闭</div>
          <div class="btns" :class="coordinatesX !== 0 && coordinatesY !== 0 ? '' : 'buttons'"
            :style="coordinatesX !== 0 && coordinatesY !== 0 ? '' : 'background-color: #8f8f94'" id="saveCanvas">确定
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Signature',
    data() {
      return {
        routers: '',
        coordinatesX: 0,
        coordinatesY: 0,
        userId: 0,
        patrolTroubleshootId: 0,
        repeat: 0,
        index: 0
      };
    },
    mounted() {
      var _this = this;
      this.userId = Number(localStorage.getItem("userId"));
      this.routers = sessionStorage.getItem('signature');
      this.patrolTroubleshootId = Number(localStorage.getItem("patrolTroubleshootId"))
      this.canvas();
      //物理返回
      // window.addEventListener("popstate", function(){
      //   _this.jumpReturn();
      // }, false);
    },
    methods: {
      //  返回签名列表
      jumpReturn() {
        this.$router.back();
      },
      //  保存
      upload(url, type) {
        let params = {
          userId: this.userId,
          patrolTroubleshootId: this.patrolTroubleshootId,
          url: url,
          type: type
        };
        this.axios.get(`${this.$global_msg.Url.host}/partroInspection/signatureSave`,
          { params }).then(res => {
            if (res.data.code === 200) {
              this.repeat = 1;
              let a = this.routers;
              this.$toast({
                message: '上传签名成功！',
                onClose: _ => {
                  this.$router.go(-1);
                }
              })
            } else {
              this.$toast('保存签名失败:' + res.data.msg)
            }
          }).catch(error => {
            this.$terminal._error(error)
          });
      },
      //  上传图片
      uploadImg(data) {
        const form_data = new FormData();
        form_data.append("multipartFile", data);
        if (data.size > 1353) {
          this.axios.post(`${this.$global_msg.Url.host}/partroInspection/uploadImg`,
            form_data).then(res => {
              if (res.data.code === 200) {
                let type;
                if (this.routers === '/signature_list') {
                  type = 1;
                } else {
                  type = 2;
                }
                this.upload(res.data.rows, type)
              } else {
                this.$toast(res.data.msg)
              }
            }).catch(error => {
              this.$terminal._error(error)
            });
        }
      },
      //  canvas获取
      canvas() {
        let a = {
          el: document.querySelector('#canvas'),
          clearEl: document.querySelector('#clearCanvas'),
          saveEl: document.querySelector('#saveCanvas')
        }
        this.lineCanvas(a);
      },
      //  画布操作
      lineCanvas(obj) {
        this.lineWidth = 2;
        this.color = '#000';
        this.background = '#fff';
        for (const index in obj) {
          this[index] = obj[index];
        }
        this.canvas = document.createElement('canvas');
        if (!(this.canvas.getContext && this.canvas.getContext('2d'))) {
          this.section = document.createElement('section');
          this.section.className = 'errorCanvas';
          this.section.innerHTML = '对不起，当前浏览器暂不支持此功能！';
          this.el.prepend(this.section);
          return;
        }
        this.canvas.width = this.el.clientWidth;
        this.canvas.height = this.el.clientHeight;
        this.el.prepend(this.canvas);
        this.setup();
        console.log(this.cxt)
        // 开始绘制
        this.canvas.addEventListener('touchstart', function (e) {
          this.cxt.beginPath();
          this.cxt.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY - 80);
        }.bind(this), false);
        // 绘制中
        this.canvas.addEventListener('touchmove', function (e) {
          this.cxt.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY - 80);
          this.coordinatesX = e.changedTouches[0].pageX
          this.coordinatesY = e.changedTouches[0].pageY
          this.cxt.stroke();
        }.bind(this), false);
        // 结束绘制
        this.canvas.addEventListener('touchend', function () {
          this.cxt.closePath();
        }.bind(this), false);
        // 清除画布
        this.clearEl.addEventListener('click', function () {
          this.setup();
          this.coordinatesX = 0
          this.coordinatesY = 0
        }.bind(this), false);
        // 保存图片
        this.saveEl.addEventListener('click', function () {
          this.index++
          if (this.index <= 1) {
            const imgPng = this.compressionSize(this.canvas.toDataURL('image/png'), 'image/png');
            const imgJpg = this.compressionSize(this.canvas.toDataURL('image/jpeg'), 'image/jpeg');
            if (imgPng !== undefined) {
              this.rotate(imgJpg).then(res => {
                this.conversion(res);
              })
              // this.conversion(imgJpg);
            } else {
              this.rotate(imgPng).then(res => {
                this.conversion(res);
              })
              // this.conversion(imgPng);
            }
          }
        }.bind(this), false);
      },
      //  处理
      rotate(data){
        return new Promise((resolve, reject) => {
          const imgView = new Image();
          imgView.src = data;
          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          const cutCoor = {sx: 0, sy: 0, ex: 0, ey: 0};
          imgView.onload = () => {
            const imgW = imgView.width;
            const imgH = imgView.height;
            const size = imgH;
            canvas.width = size * 2;
            canvas.height = size * 2;
            cutCoor.sx = size;
            cutCoor.sy = size - imgW;
            cutCoor.ex = size + imgH;
            cutCoor.ey = size + imgW;
            context.translate(size, size);
            context.rotate(Math.PI/2*3);
            context.drawImage(imgView, 0, 0);
            const imgData = context.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
            canvas.width = imgH;
            canvas.height = imgW;
            context.putImageData(imgData, 0, 0);
            resolve(canvas.toDataURL('image/jpeg'), 'image/jpeg');
          };
        });
      },
      //  压缩大小
      compressionSize(data, type) {
        let size = 0;
        const equalIndex = data.indexOf('=');  // 获取=号下标
        if (equalIndex > 0) {
          const str = data.substring(0, equalIndex); // 去除=号
          const strLength = str.length;
          const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
          size = (Math.floor(fileLength) / 1024 / 1024).toFixed(2);
        } else {
          const strLength = data.length;
          const fileLength = strLength - (strLength / 8) * 2;
          size = (Math.floor(fileLength) / 1024 / 1024).toFixed(2);
        }
        if (size < 1) {
          return this.canvas.toDataURL(type, 1);
        } else if (size > 1 && size < 2) {
          return this.canvas.toDataURL(type, 0.5);
        } else {
          return this.canvas.toDataURL(type, 0.2);
        }
      },
      //  设置
      setup() {
        this.cxt = this.canvas.getContext('2d');
        this.cxt.fillStyle = this.background;
        this.cxt.fillRect(0, 0, this.canvas.width, this.canvas.height);
        this.cxt.strokeStyle = this.color;
        this.cxt.lineWidth = this.lineWidth;
        this.cxt.lineCap = 'round'; // 线条末端添加圆形线帽，减少线条的生硬感
        this.cxt.lineJoin = 'round'; // 线条交汇时为原型边角
        // 利用阴影，消除锯齿
        this.cxt.shadowBlur = 1;
        this.cxt.shadowColor = '#000';
      },
      //  文件转换
      conversion(img) {
        // base64转blob
        const base64ToBlob = (base64Data) => {
          let arr = base64Data.split(','),
            fileType = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            l = bstr.length,
            u8Arr = new Uint8Array(l);

          while (l--) {
            u8Arr[l] = bstr.charCodeAt(l);
          }
          return new Blob([u8Arr], {
            type: fileType
          });
        };
        // blob转file
        const blobToFile = (newBlob, fileName) => {
          let files = new File([newBlob], fileName, { type: blob.type }
          );
          return files;
        };
        //  调用
        const blob = base64ToBlob(img);
        const file = blobToFile(blob, 'jpeg');
        this.uploadImg(file)
      }
    }
  }
</script>

<style scoped>
  .canvas-box {
    background-color: #f7f7f9;
    padding: 30px 20px 0;
    margin-top: 1.8519rem;
  }

  .header {
    height: 1.8519rem;
    background: #007aff;
    padding-top: 0.8333rem;
    box-sizing: border-box;
    position: fixed;
    width: 100%;
    top: 0;
    z-index: 20;
    font-size: 0.388888rem;
  }

  .title {
    padding: 0 0.3704rem;
    display: flex;
    align-items: center;
    color: #fff;
  }

  .title>div {
    width: 100%;
    font-size: 0.4444rem;
    text-align: center;
  }

  .img_zuo {
    width: 0.2593rem;
    height: 0.463rem;
  }

  /*画布*/
  #canvas {
    position: relative;
    width: 100%;
    height: calc(100vh - 4.85rem);
    border-radius: 20px;
    overflow: hidden;
  }

  #canvas canvas {
    display: block;
  }

  #saveCanvas {
    right: 0;
  }

  /*按钮*/
  .canvas-btn {
    height: 2.7rem;
  }

  .canvas-btn-box {
    background-color: #f7f7f9;
    height: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }

  .btns {
    background-color: #2b6cfe;
    width: 250px;
    line-height: 80px;
    text-align: center;
    color: #fff;
    padding: 16px 0;
    border-radius: 10px;
    transform: rotate(90deg);
  }

  .buttons {
    pointer-events: none;
  }
</style>
